#!/user/bin/python
# _*_ coding: UTF-8 _*_
# Filename: vivo.py
#!/user/bin/python
# _*_ coding: UTF-8 _*_
# Filename: Xiaomi.py
# !/user/bin/python
# _*_ coding: UTF-8 _*_
# Filename: Huawei.py
import time
import pymongo
from selenium import webdriver

client = pymongo.MongoClient('mongodb://localhost:27017')
mydb = client["jdmpresystem"]
product = mydb['Authorproducts']

driver = webdriver.Chrome()
# 修改浏览器部分属性，绕过检测。
driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
    "source": """Object.defineProperty(navigator,'webdriver',{get:()=> false})"""
})
driver.get('https://shop.vivo.com.cn/')
driver.implicitly_wait(10)  # 设置浏览器的等待（耗时） 智能化等待 加载完就不会等待
driver.maximize_window()


def drop_down():
    for x in range(1, 10, 2):
        j = x / 9
        js = 'document.documentElement.scrollTop = document.documentElement.scrollHeight * %f' % j
        driver.execute_script(js)
        time.sleep(0.5)

driver.find_element_by_css_selector('#vivo-head-wrap > div > div > div.vp-head-mainbar-pc > div.vp-head-search-btn > div > span.vp-head-search-open').click()
time.sleep(2)
driver.find_element_by_css_selector('#vivo-head-wrap > div > div > div.vp-head-mainbar-pc > div.vp-head-search-wrap > div > div > div.vp-head-search-input > input[type=text]').send_keys('手机')
driver.find_element_by_css_selector('#vivo-head-wrap > div > div > div.vp-head-mainbar-pc > div.vp-head-search-btn > div > span.vp-head-search-confirm').click()
time.sleep(1)
driver.find_element_by_css_selector('#js-result-phone').click()
for i in range(0, 12):
    drop_down()
    lis = driver.find_elements_by_xpath('/html/body/main/div[2]/div[3]/ul/li')
    for li in lis:
        skuname = li.find_element_by_xpath('p[1]').text
        price = li.find_element_by_xpath('p[2]/span').text
        price = int(price)
        comment = -1
        url = li.find_element_by_xpath('a').get_attribute('href')
        img = li.find_element_by_xpath('img').get_attribute('src')
        phone = {
            'brand':'vivo',
            'price': price,
            'comment': comment,
            'url': url,
            'skuname': skuname,
            'img': img,
            'logourl':'http://localhost:8002/ShopLogo/vo.png'
        }
        x = product.insert_one(phone)
        print(x)
        # print(phone['price'],phone['skuname'])
    if i == 11:
        break
    else:
        driver.find_element_by_css_selector('body > main > div.page-search-result-wrapper > div.search-result-content-wrapper > div.page-search-result-page > p > span.page-right-icon').click()